import json
import requests
from bs4 import BeautifulSoup as bs

class passwordError(Exception): pass

class casLogin():
    """
    login to login.bit.edu.cn
    """
    login_url = "https://login.bit.edu.cn/cas/login"

    def __init__(self, username, password):
        "args: username, password"
        self._username = username
        self._password = password
        self._session = requests.session()

    def login(self):
        "the login action, raise passwordError if the password not correct"
        response = self._session.get(self.login_url)
        soup = bs(response.text, 'html5lib')
        input_list = soup("input")
        param = {}
        for i in input_list:
            if not i.has_attr('name'): continue
            param[i['name']] = i['value']
        param['username'] = self._username
        param['password'] = self._password
        response = self._session.post(self.login_url, param)
        if not self.check_login():
            raise exceptions.passwordError

    def check_login(self):
        "check if current session is logined, return True or False"
        response = self._session.get("https://login.bit.edu.cn")
        if response.url == self.login_url:
            return False
        elif response.url == "https://login.bit.edu.cn/campus-account/myAccount/info":
            return True

    def get_session(self):
        "return the requests.Session"
        return self._session
